<!-- studyCourseMaterials.html -->
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"/>
	<meta name="format-detection" content="telephone=no, email=no, date=no, address=no">
	<title>课程资料</title>
	<link rel="stylesheet" type="text/css" href="../../css/api.css" />
	<link rel="stylesheet" type="text/css" href="../../css/weui.css" />
	<link rel="stylesheet" type="text/css" href="../../css/exceptions.css" />
	<style type="text/css">
		.contentCellDiv{
			margin-top: 0px;
		}
		.materials_title{
			margin-top: 10px;
			color: #393939;
			font-size: 14px;
		}
		.materials_content{
			padding: 10px;
			font-size: 12px;
			color: #989898;
		}
		.materials_des{
			margin-bottom: 10px;
		}
		.materials_size{
			width:60px; 
			float:left;
		}
		.materials_progress{
			overflow: hidden;
			padding: 6px;
		}
		.hide_progress{
			display:none;
		}
		/*.contentMaterialsInfo{
			padding: 10px;
			font-size: 14px;
			color: #393939;
		}
		.infoCon{
			color: #C4C4C4;
		}*/
	</style>
</head>
<body>
	<!-- <div class="contentMaterialsInfo">
		<span>资料简介</span>
		<div class="infoCon">
			<span>对应课程章节第三节，用户产品经理基础入门的文档模板书写练习，此模板为案例文档模板，读者可下载后根据自己需要进行练习。</span>
		</div>
	</div> -->
	<div class="noInternetDiv" style="text-align: center;">
        <img class="noInternetImg" src="../../image/no_network.png" alt=""></img>
        <p class="noInternetTitle">网络异常</p>
    </div>
    <div class="noDataDiv" style="text-align: center;">
        <img class="noDataImg" src="../../image/no_data.png" alt=""></img>
    </div>
	<div class="weui_cells contentCellDiv">
		
	</div>
	<!-- <div class="weui_dialog_confirm" id="prepare_download" value="">
	    <div class="weui_mask"></div>
	    <div class="weui_dialog">
	        <div class="weui_dialog_hd">
	          <strong class="weui_dialog_title">是否开始下载</strong>
	        </div>
	        <div class="weui_dialog_bd">自定义弹窗内容<br></div>
	        <div class="weui_dialog_ft">
	            <a href="javascript:;" id="cancel" class="weui_btn_dialog default">取消</a>
	            <a href="javascript:;" id="download" class="weui_btn_dialog primary">确定</a>
	        </div>
	    </div>
	</div> -->
</body>
<script src="../../script/jquery.min.js"></script>
<script type="text/javascript" src="../../script/api.js"></script>
<script type="text/javascript" src="../../script/databaseOperation.js"></script>
<script type="text/javascript" src="../../script/url.js"></script>
<script type="text/javascript">
	var isSelected;
	var isJoinCourse;
	var uid;
	var jid;
	DBReady = function(){
		prepareData();
		isJoinCourse = api.pageParam;
		isSelected = isJoinCourse.selected;

		var canDownload = false;
		// $('.prepare_download').hide();
		// 
		loadDataFailShowPageFun = function(data){
			var connectionType = api.connectionType;
			if(connectionType != 'none'){
				$api.css($api.dom('.noInternetDiv'), 'display:none;');
				if(data.length == 0){
					$api.css($api.dom('.noDataDiv'), 'display:block;');
				}
				else{
					$api.css($api.dom('.noDataDiv'), 'display:none;');
				}
			}
			else{
				$api.css($api.dom('.noDataDiv'), 'display:none;');
				if(data.length == 0){
					$api.css($api.dom('.noInternetDiv'), 'display:block;');
				}
				else{
					$api.css($api.dom('.noInternetDiv'), 'display:none;');
				}
			}
		}
		
		// function startDownload(dataPro){
		// 	if (canDownload == true) {
				

		// 		$progress.animate({'width' : "100%"}, 5000);
		// 	}
		// }
		// 
		// 
		// 
		// 
		api.addEventListener({
		    name: 'filesDownloadFinishNotifi'
		}, function(ret, err){
		});
		// removeComment
        api.addEventListener({
            name: 'removeComment'
        }, function(ret, err){
            
        });
        api.addEventListener({
            name: 'allChapterStudiedNotifi'
        }, function(ret, err){
        });
        api.addEventListener({
            name: 'studyPassedExamNotifi'
        }, function(ret, err){
        });
        // loadCommentListData
		api.addEventListener({
            name: 'loadCommentListData'
        }, function(ret, err){
            
        });
        // api.addEventListener({
        //     name: 'courseDesNotifi'
        // }, function(ret, err){
        // });
        api.addEventListener({
            name: 'downlaodFailedNotifi'
        }, function(ret, err){
        });
		api.addEventListener({
 	        name: 'selectedCourseNotifi'
 	    }, function(ret, err){
 	        isSelected = ret.value.selected;
 	    });

		var getRequestData = new Array();
		// 
		// 
		// 获得请求数据，插入数据库
		// // 防止只插入最后一条语句
		insertMaterialsDataCallBackFun = function(insertStr,callBack){
			openDB(function(ret,err){
				if(ret.status){
					callBack(insertStr);
				}
			})
		}
		insertMaterialsData = function (dataArr) {
			// body...
			// 插入数据成功，查询  t_study_course_data
            // openDB(function(ret,err){
                // if(ret.status){
                    var j = 0;
                    if(dataArr.length > 0){
                    	for (var i = 0; i < dataArr.length; i++) {
	                        var insertMaterialsParam={
	                            cid: dataArr[i].vcid,
	                            data_id: dataArr[i].id,
	                            names: dataArr[i].names,
	                            real_url: dataArr[i].realurl,
	                            size: dataArr[i].size,
	                            ctime: dataArr[i].ctime,
	                            vid: dataArr[i].vid,
	                            vcid: dataArr[i].vcid,
	                            sort: dataArr[i].sort,
	                            material: dataArr[i].material
	                        }
	                        insertMaterialsDataCallBackFun(insertMaterialsParam,function(insertParam){
		                    	insertData('t_study_course_data', insertParam, function(ret, err){
				                	// alert('插入'+JSON.stringify( insertParam )+ '成功' + JSON.stringify( err ));
		                            if (ret.status) {
		                                // alert('插入成功' + planid + ret.status);
		                            }
		                            else{
		                                // alert(err.msg+$api.getStorage('uid')+planid);
		                            }
		                            j++;
		                            if(j == dataArr.length){
										selectMaterialsData();
				                    }
		                        });
		                    });
		                    // j++;
                      //       if(j == dataArr.length){
		                    //     closeDB(function(ret, err){
		                    //         if (ret.status) {
		                    //             // alert('关闭数据库' + ret.status);
		                    //             // selectMaterialsData();
		                    //             // showPageData(dataArr);
		                    //         }
		                    //     });
		                    // }
		                }
                    }
                    else{
                    	selectMaterialsData();
                    	// closeDB(function(ret, err){
                     //        if (ret.status) {
                     //            // alert('关闭数据库' + ret.status);
                     //            // selectMaterialsData();
                     //        }
                     //    });
                    }
	            // }
            // })
		} 
		// 
		// 
		// 插入数据库成功后，查询数据，显示在页面上
		selectMaterialsData = function () {
			// body...
			// 查询成功，页面展示  t_study_course_data
			openDB(function(ret, err){
	            if (ret.status) {
	            	var selectSqlString = 'select * from t_study_course_data where vcid='+isJoinCourse.cid;
	                selectSQL(selectSqlString, function(ret, err){
	                    if (ret.status) {
	                        var data = ret.data;
	                        // for (var i = 0; i < data.length; i++) {
	                            
	                        // }
	                        showPageData(data);
	                    }
	                    else{
	                    	// alert(JSON.stringify( err ));
	                    }
	                    // closeDB(function(ret, err){
	                    //     if (ret.status) {
	                    //         // alert('关闭数据库' + ret.status);
	                    //     }
	                    // });
	                    
	                });
	            }
	        });
		}
		// 
		// 
		// 给页面元素赋值
		showPageData = function (dataArr) {
			loadDataFailShowPageFun(dataArr);
			// var materialsName = new Array('产品分析在产品工作中的应用.docx','BRD文档通用模板.docx','visio汉化破解版下载.zip');
			// var materialsInfo = new Array('暂无资料简介','对应课程章节第三节，用户产品经理基础入门的文档模板书写练习，此模板为案例文档模板，读者可下载后根据自己需要进行练习。','暂无资料简介');
			// var materialsSize = new Array('200KB','3.15MB','46.1MB');
			// alert(JSON.stringify(dataArr));
			for (var i = 0; i < dataArr.length; i++) {
				var vcid = dataArr[i].vcid;
				var data_id = dataArr[i].data_id;
				var is_downloaded = dataArr[i].is_downloaded;
				var real_url = dataArr[i].real_url;
				var names = dataArr[i].names;
				var material = dataArr[i].material;
				var downloadStatus = "";
				if (is_downloaded == '1') {//已下载
					downloadStatus = " hide_progress";
				}
				$('.contentCellDiv').append('<div class="weui_cell" progress_id="'+data_id+'" names="' + names + '" vcid="' + vcid + '" real_url="' + real_url + '"><div class="weui_cell_bd weui_cell_primary"><div class="materials_title">'+(i+1)+'.'+names+'</div><div class="materials_content"><div class="materials_des">'+material+'</div><div class="materials_download"><div class="materials_size"><span>'+bytesToSize(dataArr[i].size)+'</span></div><div id="prodiv' + data_id + '" class="materials_progress' + downloadStatus + '"><div class="container"><div class="weui_progress"><div class="weui_progress_bar"><div class="weui_progress_inner_bar" id="'+data_id+'" style="width: 0;"></div></div></div></div></div></div></div></div></div>');
			}
			// 获取该课程是否已加入学习,若未加入，则不显示进度条(即不可下载)
			// if(isSelected == '0'){
			// 	$('.materials_progress').hide();
			// }
			// else{
			// 	$('.materials_progress').show();
			// }
			
			$('.weui_cell').click(function(){
				if (isSelected == 0) {//如果未选当前课程则不能学习
					api.toast({
					    msg: '你还没有添加该课程',
					    duration: 3000,
					    location: 'bottom'
					});
					return;
				}
				// if(isJoinCourse.isadded == '1'){
					var data_id = $(this).attr('progress_id');
					var prodivID = '#prodiv' + data_id;
					var vcid = $(this).attr('vcid');
					var names = $(this).attr('names');
					var real_url = $(this).attr('real_url');
					if ($(prodivID).hasClass('hide_progress')) {
						var filepath = api.cacheDir + '/download/' + vcid + '/' + names;
						var filetype = /\.[^\.]+$/.exec(names); 
						if (filetype == '.rar' || filetype == '.zip' || filetype == '.exe') {
							api.toast({
							    msg: '暂不支持该格式',
							    duration: 2000,
							    location: 'bottom'
							});
						}else{
//						  alert(filepath);
						  if(filetype == '.mp4'||filetype == '.mp3' ){
						  var studyParam = {
								    	videourl : filepath,
								    	imgurl : '',
								    	videoname : names,
								    	vid : vcid,
								    	cid :vcid,
								    	pid : vcid,
								    	ctime : 1,
								    	etime : 1,
								    	status : 1,
								    	cstatus:1,
								    	checks : 0,
								    	crid : "",
								    	examid : ""
								    };
//							     alert('章节参数' + JSON.stringify(studyParam));
								api.openWin({useWKWebView:true,
								    name: 'study_videoPlay_Material',
								    url: 'study_videoPlay_Material.html',
								    bounces: false,
								    slidBackEnabled : false,
								    pageParam: studyParam
								});
					              
						  
						
						  }	 else if(filetype == '.pdf' ){
						       var pdfReader = api.require('pdfReader');
								pdfReader.open({
								   path:filepath
								});
						  
						  
						  } else{
//						   alert(filepath);
							var docReader = api.require('docReader');
							docReader.open({
							    path:filepath
							});
							}
						}
					}else{
						api.sendEvent({
						    name: 'downloadMaterial',
						    extra: {
						    	vcid : vcid,
						    	realurl : real_url,
						    	dataid : data_id,
						    	names : names
						    }
						});
					}
					// var progressID = '#' + data_id;
					// var $progress = $(progressID);

					// $progress.animate({'width' : "100%"}, 5000);
				// openDB(function(ret, err){
				// 	if (ret.status) {
				// 		var sql = "SELECT is_downloaded FROM t_study_course_data WHERE vcid='" + vcid + "';";
				// 		selectSQL(sql, function(ret, err){
				// 			if (ret.status && ret.data != null && ret.data != '' && ret.data != undefined) {
				// 				var is_downloaded = ret.data[0].is_downloaded;
								
				// 			}
				// 		});
				// 	}
				// });
			});

		}
		//下载中的资料的通知
		api.addEventListener({
		    name: 'downloadingMaterialNotifi'
		}, function(ret, err){
			// alert('资料页面' + JSON.stringify(ret));
			var result = ret.value.ret;
			var dataid = ret.value.dataid;
			var prodivID = '#prodiv' + dataid;
			var progressID = '#' + dataid;
			var width = "width:" + result.percent + "%;";
			$(progressID).attr('style', width);
			if (result.state == 1) {
				$(prodivID).addClass('hide_progress');
				openDB(function(ret, err){
					if (ret.status) {
						var sql = "UPDATE t_study_course_data SET is_downloaded = '1', localpath = '" + result.savePath + "' WHERE data_id = '" + dataid + "';";
						// alert(sql);
						executeSQL(sql, function(ret, err){
							// alert('ret:'+JSON.stringify(ret)+'\n'+'err:'+JSON.stringify(err));
						});
					}
				});
			}
		});

		// 
		// 
		// 
		// 
		api.showProgress({
			style : 'default',
			animationType : 'fade',
			title : '加载中...',
			modal : false
		});
		// 数据请求
		requestMaterialsData = function(){
			var materialsParam = {
				uid: uid,
	            jid: jid,
				cid: isJoinCourse.cid
				// cstatus:isJoinCourse.cstatus
			
			}
			//'http://cfnet.org.cn/index2.php?m=Android&c=Freecourse&a=getfilelist'
			
			api.ajax({
			    url: study_course_data,
			    method: 'post',
			    timeout: 30,
			    dataType: 'json',
			    returnAll:false,
			    data:{
			    	values: materialsParam
			    }
			},function(ret,err){
				api.hideProgress();
				// alert(study_course_data);
				// alert(JSON.stringify(materialsParam));
				// alert(JSON.stringify(ret));
			    if (ret) {
			        // TODO 
			        if(ret.list){
			        	getRequestData = ret.list;
			        }
			        // alert(JSON.stringify( getRequestData ));
		        	// 请求数据成功，将数据插入数据库
		        	insertMaterialsData(getRequestData);
		        	// showPageData(getRequestData);
			    } else {
			        // api.alert({
			        //     msg:('错误码：'+err.code+'；错误信息：'+err.msg+'网络状态码：'+err.statusCode)
			        // });
			        selectMaterialsData();
			    };
			});
		}
		requestMaterialsData();


		
	}
	//转换字节
	function bytesToSize(bytes) {
		if (bytes === 0)
			return '0 B';
		var k = 1000, // or 1024
		sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], i = Math.floor(Math.log(bytes) / Math.log(k));
		return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
	}
	function prepareData(){
		uid = $api.getStorage('cfnetppuid');
		jid = $api.getStorage('cfnetppjxid');
	}
</script>
</html>
